<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('店铺购买页面')"/>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 select-table table-striped">
            <div class="btn-group-sm" id="toolbar" role="group" style="margin-top: 15px">
                <a class="btn btn-success" onclick="$.operate.addToCart()" shiro:hasPermission="system:addToCart">
                    <i class="fa fa-cart-plus"></i> 添加到购物车
                </a>
                <a class="btn btn-danger" onclick="$.operate.remove()" shiro:hasPermission="system:remove" disabled>
                    <i class="fa fa-minus"></i> 移除
                </a>
            </div>
            <div class="tabs-container" style="margin-top: 15px">
                <div class="tabs-left">
                    <ul class="nav nav-tabs">
                        <li class="active"><a data-toggle="tab" href="#tab-dessert"> 甜品</a>
                        </li>
                        <li class=""><a data-toggle="tab" href="#tab-setMeal"> 套餐</a>
                        </li>
                    </ul>
                    <div class="tab-content">
                        <div id="tab-dessert" class="tab-pane active">
                            <div class="panel-body">
                                <table id="bootstrap-table-dessert" class="table table-striped"></table>
                            </div>
                        </div>
                        <div id="tab-setMeal" class="tab-pane">
                            <div class="panel-body">
                                <table id="bootstrap-table-setMeal" class="table table-striped"></table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 购物车面板 - 固定定位在底部 -->
            <div class="col-sm-12" style="padding: 15px;">
                <div class="panel panel-info">
                    <div class="panel-heading">购物车</div>
                    <div class="panel-body">
                        <p id="cart-items">当前购物车为空</p>
                        <p id="total-value">总价值：0 元</p>
                        <!-- 加入结算按钮 -->
                        <button id="settlementButton" class="btn btn-primary">结算</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    var editDessertFlag = [[${@permission.hasPermi('system:dessert:edit')}]];
    var removeDessertFlag = [[${@permission.hasPermi('system:dessert:remove')}]];
    var editSetMealFlag = [[${@permission.hasPermi('system:setMeal:edit')}]];
    var removeSetMealFlag = [[${@permission.hasPermi('system:setMeal:remove')}]];

    var prefixDessert = ctx + "system/product";
    var prefixSetMeal = ctx + "system/setmeal";
    var createOrderUrl = ctx + "system/shopping/create";
    var cartMap = {};

    function updateCartItems(cartData) {
        console.log("cartData:{}", JSON.stringify(cartData))
        console.log("cartMap:{}", JSON.stringify(cartMap))
        var itemsText = '';
        var totalValue = 0;
        for (var item of cartData) {
            if (item.type === 'add') {
                if (cartMap[item.id + '_' + item.proType]) {
                    console.log("add...")
                    cartMap[item.id + '_' + item.proType].quantity++;
                } else {
                    cartMap[item.id + '_' + item.proType] = {
                        name: item.name,
                        price: item.price,
                        quantity: 1,
                        proType: item.proType
                    };
                }
            } else if (item.type === 'remove') {
                console.log("remove...")
                if (cartMap[item.id + '_' + item.proType] && cartMap[item.id + '_' + item.proType].quantity > 0) {
                    cartMap[item.id + '_' + item.proType].quantity--;
                    if (cartMap[item.id + '_' + item.proType].quantity === 0) {
                        delete cartMap[item.id + '_' + item.proType];
                    }
                }
            }
        }

        for (var itemName in cartMap) {
            console.log("itemName :", itemName);
            var item = cartMap[itemName];
            itemsText += item.name + '*' + item.quantity + ', ';
            totalValue += item.price * item.quantity;
        }

        itemsText = itemsText.slice(0, -2); // 去除最后多余的逗号和空格

        $('#cart-items').text(itemsText);
        $('#total-value').text('总价值：' + totalValue + ' 元');
    }

    // 为结算按钮添加点击事件
    $('#settlementButton').click(function () {
        var cartData = [];
        for (var itemName in cartMap) {
            var item = cartMap[itemName];
            cartData.push({
                id: itemName,
                proType: item.proType,
                quantity: item.quantity
            });
        }
        var totalValueText = $('#total-value').text();
        var totalValue = parseFloat(totalValueText.match(/\d+\.\d+|\d+/)[0]);
        $.ajax({
            type: 'POST',
            url: createOrderUrl,
            dataType: 'json',
            data: JSON.stringify({
                shoppingDTOList: cartData
            }),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                console.log(JSON.stringify({
                    shoppingDTOList: cartData
                }))
                // 弹窗提示
                alert('订单创建成功');
            },
            error: function (error) {
                console.log(error);
            }
        });
    });


    $(function () {
        var optionsDessert = {
            method: 'POST',
            url: prefixDessert + "/list",
            removeUrl: prefixDessert + "/remove",
            modalName: "甜品",
            columns: [{
                checkbox: true
            },
                {
                    field: 'index',
                    title: '序号',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    field: 'id',
                    title: '主键'
                },
                {
                    field: 'productName',
                    title: '商品名称'
                },
                {
                    field: 'productPrice',
                    title: '售价'
                },
                {
                    field: 'productScore',
                    title: '商品积分'
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.addToCart(\'' + row.id + '\', \'' + row.productName + '\', \'' + row.productPrice + '\',\'' + '0' + '\')">添加到购物车</a> ');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\', \'' + '0' + '\')" ' + (!cartMap[row.productName] ? 'disabled="disabled"' : '') + '>移除</a>');
                        return actions.join('');
                    }
                }]
        };
        $('#bootstrap-table-dessert').bootstrapTable(optionsDessert);

        var optionsSetMeal = {
            method: 'POST',
            url: prefixSetMeal + "/list",
            removeUrl: prefixSetMeal + "/remove",
            modalName: "套餐",
            columns: [{
                checkbox: true
            },
                {
                    field: 'index',
                    title: '序号',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    field: 'id',
                    title: '主键'
                },
                {
                    field: 'setmealName',
                    title: '套餐名'
                },
                {
                    field: 'setmealPrice',
                    title: '套餐价格'
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.addToCart(\'' + row.id + '\', \'' + row.setmealName + '\', \'' + row.setmealPrice + '\', \'' + '1' + '\')">添加到购物车</a> ');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\', \'' + '1' + '\')" ' + (!cartMap[row.setmealName] ? 'disabled="disabled"' : '') + '>移除</a>');
                        return actions.join('');
                    }
                }]
        };
        $('#bootstrap-table-setMeal').bootstrapTable(optionsSetMeal);
    });

    // 添加到购物车的操作函数
    $.operate.addToCart = function (id, name, price, proType) {

        updateCartItems([{id: id, name: name, price: price, type: "add", proType: proType}]);
    };

    // 移除的操作函数
    $.operate.remove = function (id, proType) {
        console.log("移除购物车 :", id);
        // 这里实现移除的逻辑
        updateCartItems([{id: id, type: "remove", proType: proType}]);
    };
</script>
</body>
</html>